<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()

type ProductItem = {
  id: number
  productNumber: string
  productName: string
  specificationModel: string
  unit: string
  productType: string
  productAttribute: string
  productClassification: string
  activationStatus?: boolean | number | string
  image?: string
  attachment?: string
}

const readClient = ReadClients[3]
const writeClient = WriteClients[3]

const queryForm = reactive({
  keyword: '',              // 产品名称关键词
  categoryId: '' as string | number, // 产品分类（如有字典可替换）
  productType: '' as string | number,
  productAttr: '' as string | number,
  status: '' as string | boolean, // '' | true | false
})

// 控制“更多”展开/收起
const showMore = ref(false)

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const loading = ref(false)
const tableData = ref<ProductItem[]>([])
// 移除事件定义，改为路由跳转

async function fetchList() {
  loading.value = true
  try {
    const res = await readClient.get('/productread/api/Product/ProductShow', {
      params: {
        pageIndex: pagination.pageIndex,
        pageSize: pagination.pageSize,
        ProductName: queryForm.keyword || undefined,
        ProductType: queryForm.productType || undefined,
        ActivationStatus: typeof queryForm.status === 'boolean' ? queryForm.status : undefined,
        ProductAttribute: queryForm.productAttr || undefined,
        ProductClassification: queryForm.categoryId || undefined,
      },
    })
    const payload = res?.data ?? {}
    const data = payload.data ?? payload
    const items = data.data ?? data.items ?? data.rows ?? data.list ?? []
    const total = data.total ?? data.totalCount ?? data.count ?? (Array.isArray(items) ? items.length : 0) ?? 0

    // 取第一个非空字段
    const pickFirst = (obj:any, keys:string[])=>{
      for(const k of keys){
        const v = obj?.[k]
        if(v !== undefined && v !== null) return v
      }
      return undefined
    }

    const normalized = (Array.isArray(items) ? items : []).map((it:any)=>{
      const pick = (keys:string[])=> pickFirst(it, keys)
      return {
        id: pick(['id','ID','Id']),
        productNumber: pick(['productNumber','ProductNumber','product_no','productnumber']),
        productName: pick(['productName','ProductName','name','productname']),
        specificationModel: pick(['specificationModel','SpecificationModel','spec']),
        unit: pick(['unit','Unit']),
        productType: pick(['productType','ProductType','producttype']),
        productAttribute: pick(['productAttribute','ProductAttribute','productattribute']),
        productClassification: pick(['productClassification','ProductClassification','productclassification']),
        activationStatus: pick(['activationStatus','ActivationStatus','enabled','Enable','activationstatus']),
        image: pick(['image','Image']),
        attachment: pick(['attachment','Attachment']),
      }
    }) as ProductItem[]
    tableData.value = normalized
    pagination.total = total
  } catch (err) {
    ElMessage.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

function handleSearch(){ pagination.pageIndex = 1; fetchList() }
function handleReset(){ queryForm.keyword=''; queryForm.categoryId=''; pagination.pageIndex=1; fetchList() }
function handlePageChange(p:number){ pagination.pageIndex=p; fetchList() }
function handleSizeChange(s:number){ pagination.pageSize=s; pagination.pageIndex=1; fetchList() }

async function handleRemove(row: ProductItem){
  try{
    await ElMessageBox.confirm(`确认删除【${row.productName}】吗？`, '提示', { type:'warning' })
    
    // 先删除产品记录
    await writeClient.get('/productwrite/api/Product/DeleteProduct', { params: { Id: row.id } })
    
    // 删除云端文件
    if (row.image) {
      try {
        await writeClient.post('/productwrite/api/Upload/DeleteFile', null, { params: { url: row.image } })
      } catch (err) {
        console.warn('删除图片失败:', err)
      }
    }
    
    if (row.attachment) {
      try {
        await writeClient.post('/productwrite/api/Upload/DeleteFile', null, { params: { url: row.attachment } })
      } catch (err) {
        console.warn('删除附件失败:', err)
      }
    }
    
    ElMessage.success('删除成功')
    fetchList()
  }catch{}
}

function handleEdit(row: ProductItem){ 
  router.push({ name: 'ProductEdit', query: { id: row.id, origin: 'list' } })
}
function handleCreate(){ 
  router.push({ name: 'ProductCreate' })
}
function handleDetail(row: ProductItem){ 
  router.push({ name: 'ProductDetail', query: { id: row.id } })
}
function handleImport(){ /* import handler to be implemented */ }
async function handleExport(){
  try{ 
    // 使用 window.location.href 直接触发下载
    const downloadUrl = `${readClient.defaults.baseURL}/api/Product/ExportExcelProduct`
    window.location.href = downloadUrl
    ElMessage.success('导出任务已发起') 
  }catch{ 
    ElMessage.error('导出失败') 
  }
}

onMounted(fetchList)
</script>

<template>
  <div class="product-page">
    <el-card class="toolbar">
      <!-- 顶部可折叠区（上方三个，默认收起，点击“更多”向上展开） -->
      <transition name="expand">
        <div class="toolbar-row top-extra" v-show="showMore">
          <div class="filters extra">
            <el-select v-model="queryForm.productType" placeholder="请选择产品类型" clearable class="flt top">
              <el-option label="半成品" value="半成品" />
              <el-option label="成品" value="成品" />
              <el-option label="其他" value="其他" />
            </el-select>
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable class="flt top">
              <el-option label="全部" :value="undefined" />
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          <el-select v-model="queryForm.productAttr" placeholder="请选择产品属性" clearable class="flt top">
              <el-option label="自制" value="自制" />
              <el-option label="委外" value="委外" />
              <el-option label="外购" value="外购" />
              <el-option label="其他" value="其他" />
            </el-select>
          </div>
        </div>
      </transition>

      <!-- 主行（固定显示）：输入 + 类别；右侧 重置 / 查询 / 更多(带方向) -->
      <div class="toolbar-row main">
        <div class="filters main">
          <el-input v-model="queryForm.keyword" placeholder="请输入产品名称" clearable class="flt" size="large" />
          <el-select v-model="queryForm.categoryId" placeholder="请选择产品分类" clearable class="flt" size="large">
            <el-option label="分类一" :value="1" />
            <el-option label="分类二" :value="2" />
          </el-select>
        </div>
        <div class="toolbar-actions">
          <el-button size="large" plain @click="handleReset">重置</el-button>
          <el-button size="large" type="primary" @click="handleSearch">查询</el-button>
          <el-button size="large" text @click="showMore = !showMore">
            更多
            <el-icon style="margin-left:4px">
              <component :is="showMore ? ArrowUp : ArrowDown" />
            </el-icon>
          </el-button>
        </div>
      </div>
    </el-card>

    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <div class="title">物料管理</div>
        </div>
      </template>
      <div class="action-bar">
        <el-button size="large" type="primary" @click="handleCreate">新增</el-button>
        <el-button size="large" @click="handleImport">导入</el-button>
        <el-button size="large" @click="handleExport">导出</el-button>
      </div>
      <el-table :data="tableData" v-loading="loading" class="compact-table">
        <el-table-column type="selection" width="48" />
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">{{ (pagination.pageIndex-1)*pagination.pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="productNumber" label="产品编号" min-width="180">
          <template #default="scope">
            <el-link type="primary" underline="hover" @click="handleDetail(scope.row)">{{ scope.row.productNumber }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="specificationModel" label="规格型号" min-width="160" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="productType" label="产品类型" min-width="140" show-overflow-tooltip />
        <el-table-column prop="productAttribute" label="产品属性" min-width="140" show-overflow-tooltip />
        <el-table-column prop="productClassification" label="产品分类" min-width="160" show-overflow-tooltip />
        <el-table-column label="启用状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.activationStatus ? 'success' : 'info'">{{ scope.row.activationStatus ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleEdit(scope.row)">编辑</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" :underline="false" @click="handleRemove(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :page-sizes="[10,20,30,50]"
          :page-size="pagination.pageSize"
          :current-page="pagination.pageIndex"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.product-page{ display:flex; flex-direction:column; gap:12px; }
.toolbar{ padding-bottom:8px; }
.toolbar-row{ display:flex; align-items:center; justify-content:space-between; gap:12px; }
.toolbar-row.main{ padding-top:8px; }
.filters{ display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
.filters.main{ flex: 1; }
.filters.extra{ width: 100%; }
.flt{ width:260px; }
.top.flt{ width:220px; }
.toolbar-actions{ display:flex; align-items:center; gap:8px; }
.spacer{ width:220px; height:1px; visibility:hidden; }

/* 展开/收起动画（向上区域） */
.expand-enter-from, .expand-leave-to{ height:0; opacity:0; }
.expand-enter-to, .expand-leave-from{ height:44px; opacity:1; }
.expand-enter-active, .expand-leave-active{ transition: all .2s ease-in-out; overflow:hidden; }
.list-card{ padding-bottom:8px; }
.pagination{ margin-top:12px; display:flex; justify-content:flex-end; }

/* 对齐与留白：让输入与下拉宽度一致、行内垂直对齐 */
.filters :deep(.el-input),
.filters :deep(.el-select){
  vertical-align: middle;
}

/* 卡片标题更清晰 */
.list-header{ padding: 2px 0; }

/* 列表操作条：与截图一致放在标题下，左对齐 */
.action-bar{ display:flex; gap:8px; padding: 0 0 8px 0; }

/* 表格更紧凑 */
.compact-table :deep(.el-table__header th),
.compact-table :deep(.el-table__body td){
  padding: 8px 8px;
}
</style>


